package cn.itcast.web.task;

import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.cargo.Export;
import cn.itcast.domain.cargo.ExportExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.cargo.ExportService;
import cn.itcast.service.system.UserService;
import cn.itcast.vo.ExportResult;
import cn.itcast.web.mq.MailProducer;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.shiro.crypto.hash.Hash;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 定时执行此类中的方法
 */
public class ExportJob {

	@Reference
	private ExportService exportService;

	@Reference
	private ContractService contractService;

	@Autowired
	private UserService userService;

	@Autowired
	private MailProducer mailProducer;

	/**
	 * 每5秒打印时间
	 *  java方法只关心业务逻辑：打印系统时间
	 *  1.没有参数
	 *  2.没有返回值
	 */
	public void execute() {
		//1.查询数据库中状态=2的所有报运单（已经发送到海关，没有结果） List<Export> list
		ExportExample example = new ExportExample();
		ExportExample.Criteria criteria = example.createCriteria();
		criteria.andStateEqualTo(2l);
		List<Export> list = exportService.findAll(example);
		//2.循环所有商品对象，调用海关平台获取数据响应 ExportResult对象（包含所有商品的税）
		for (Export export : list) {
			WebClient wc = WebClient.create("http://localhost:9001/ws/export/ep/"+export.getId());
			ExportResult result = wc.get(ExportResult.class);
			//3.判断保运状态（不等于2调用service更新报运单和商品的信息）
			if(result.getState() != 2) { //已经具有保运结果
				exportService.updateE(result);
			}
		}
	}

	public void reminder(){
		//1.查询快要到期的货物
		String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
		List<Contract> contracts = contractService.findContractForDelivery(date);
		if(contracts!= null && contracts.size()>0) {
			for (Contract contract : contracts) {
				User  user = userService.findByCompanyIdAndDegree(contract.getCompanyId(),1);

				String to = user.getEmail();
				String subject= "到期提醒";
				String content= "尊敬的用户:"+user.getUserName()+",您有合同即将到期,请速去处理,合同号:"+contract.getContractNo();
				Map map = new HashMap<>();
				map.put("to",to);
				map.put("subject",subject);
				map.put("content",content);
				mailProducer.sendMag(map);
			}
		}
	}


	public void smsSend(){
		//查询要过生日的用户
		String date = new SimpleDateFormat("MM-dd").format(new Date());
		date = "12-05";
		List<User> users = userService.findByBirthDay(date);
		for (User user : users) {
			String telephone = user.getTelephone();
			String message= "888888";
			Map map = new HashMap<>();
			map.put("telephone",telephone);
			map.put("message",message);
			mailProducer.sendSms(map);
		}

	}


}
